<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />



  <link rel="icon" type="image/png" sizes="32x32" href="/images/lss.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/lss.png?v=5.1.3">






  <meta name="keywords" content="Android,WebView," />





  <link rel="alternate" href="/atom.xml" title="Leason's Blog" type="application/atom+xml" />






<meta name="description" content="WebView 是Android开发中经常会用到的功能，是一个基于webkit引擎，用于显示来自本地、服务器web页面的控件，可以很好的提升应用扩展性。有以下优点：   可以直接显示和渲染web页面 webview可以直接用html文件（网络上或本地assets中）作布局 和JavaScript交互调用   基本使用方法在 安卓开发文档 中已经做了相关的详细介绍，这里主要根据日常开发中需求，整理了">
<meta name="keywords" content="Android,WebView">
<meta property="og:type" content="article">
<meta property="og:title" content="如何优雅的使用WebView">
<meta property="og:url" content="http://www.leason.top/2018/01/09/如何优雅的使用WebView/index.html">
<meta property="og:site_name" content="Leason&#39;s Blog">
<meta property="og:description" content="WebView 是Android开发中经常会用到的功能，是一个基于webkit引擎，用于显示来自本地、服务器web页面的控件，可以很好的提升应用扩展性。有以下优点：   可以直接显示和渲染web页面 webview可以直接用html文件（网络上或本地assets中）作布局 和JavaScript交互调用   基本使用方法在 安卓开发文档 中已经做了相关的详细介绍，这里主要根据日常开发中需求，整理了">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-02-28T01:56:24.120Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="如何优雅的使用WebView">
<meta name="twitter:description" content="WebView 是Android开发中经常会用到的功能，是一个基于webkit引擎，用于显示来自本地、服务器web页面的控件，可以很好的提升应用扩展性。有以下优点：   可以直接显示和渲染web页面 webview可以直接用html文件（网络上或本地assets中）作布局 和JavaScript交互调用   基本使用方法在 安卓开发文档 中已经做了相关的详细介绍，这里主要根据日常开发中需求，整理了">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.3',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.leason.top/2018/01/09/如何优雅的使用WebView/"/>





  <title>如何优雅的使用WebView | Leason's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?54e6baee06451ba85d4c15e0bb37e425";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Leason's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">All is flux,nothing stays still</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.leason.top/2018/01/09/如何优雅的使用WebView/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Leason">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/pics.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Leason's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">如何优雅的使用WebView</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-09T09:55:20+08:00">
                2018-01-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/开发/" itemprop="url" rel="index">
                    <span itemprop="name">开发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/01/09/如何优雅的使用WebView/" class="leancloud_visitors" data-flag-title="如何优雅的使用WebView">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><a href="https://developer.android.google.cn/reference/android/webkit/WebView.html" target="_blank" rel="noopener"><strong>WebView</strong></a> 是Android开发中经常会用到的功能，是一个基于webkit引擎，用于显示来自本地、服务器web页面的控件，可以很好的提升应用扩展性。有以下优点：</p>
<blockquote>
<ul>
<li>可以直接显示和渲染web页面</li>
<li>webview可以直接用html文件（网络上或本地assets中）作布局</li>
<li>和JavaScript交互调用</li>
</ul>
</blockquote>
<p>基本使用方法在 <a href="https://developer.android.google.cn/reference/android/webkit/WebView.html" target="_blank" rel="noopener"><strong>安卓开发文档</strong></a> 中已经做了相关的详细介绍，这里主要根据日常开发中需求，整理了以下3个方面。</p>
<a id="more"></a>
<h3 id="一、处理web页面中的图片点击事件"><a href="#一、处理web页面中的图片点击事件" class="headerlink" title="一、处理web页面中的图片点击事件"></a>一、处理web页面中的图片点击事件</h3><p>在应用中使用 <strong>WebView</strong> 加载网页进行显示的时候，多数情况下都要进行内容适配，这会导致图片进行一定比例的缩小，在手机上看起来模糊，影响用户体验。我们可以提取出网页中的关键图片添加点击事件，然后对图片进行自定义处理，比如：放大、旋转等。</p>
<h4 id="1-定义JavaScript接口类"><a href="#1-定义JavaScript接口类" class="headerlink" title="1.定义JavaScript接口类"></a>1.定义JavaScript接口类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaScriptInterface</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Context context;</span><br><span class="line">    </span><br><span class="line">    JavaScriptInterface(Context context) &#123;</span><br><span class="line">        <span class="keyword">this</span>.context = context;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//点击图片的回调方法</span></span><br><span class="line">    <span class="comment">//必须添加JavascriptInterface注解,否则无法响应</span></span><br><span class="line">    <span class="meta">@JavascriptInterface</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">openImage</span><span class="params">(String img)</span> </span>&#123;</span><br><span class="line">        Intent intent = <span class="keyword">new</span> Intent();</span><br><span class="line">        <span class="comment">//这里获取到的是图片地址</span></span><br><span class="line">        intent.putExtra(<span class="string">"image"</span>, img);</span><br><span class="line">        <span class="comment">//跳转到图片处理页面</span></span><br><span class="line">        intent.setClass(context, ImageActivity.class);</span><br><span class="line">        context.startActivity(intent);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="2-在WebView中添加JavascriptInterface"><a href="#2-在WebView中添加JavascriptInterface" class="headerlink" title="2.在WebView中添加JavascriptInterface"></a>2.在WebView中添加JavascriptInterface</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">JavaScriptInterface javascriptInterface = <span class="keyword">new</span> JavaScriptInterface(context);</span><br><span class="line">webview.addJavascriptInterface(javascriptInterface, <span class="string">"imagelistener"</span>);</span><br></pre></td></tr></table></figure>
<h4 id="3-新建图片遍历和处理的方法"><a href="#3-新建图片遍历和处理的方法" class="headerlink" title="3.新建图片遍历和处理的方法"></a>3.新建图片遍历和处理的方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">addImageClickListener</span><span class="params">(WebView view)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 遍历所有的img节点,添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去</span></span><br><span class="line">        view.loadUrl(<span class="string">"javascript:(function()&#123;"</span> +</span><br><span class="line">                <span class="string">"var objs = document.getElementsByTagName(\"img\"); "</span> +</span><br><span class="line">                <span class="string">"for(var i=0;i&lt;objs.length;i++)  "</span> +</span><br><span class="line">                <span class="string">"&#123;"</span></span><br><span class="line">                + <span class="string">"    objs[i].onclick=function()  "</span> +</span><br><span class="line">                <span class="string">"    &#123;  "</span></span><br><span class="line">                + <span class="string">"        window.imagelistner.openImage(this.src);  "</span> +</span><br><span class="line">                <span class="string">"    &#125;  "</span> +</span><br><span class="line">                <span class="string">"&#125;"</span> +</span><br><span class="line">                <span class="string">"&#125;)()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//循环遍历接收到的数据,提取出带有”img”标签的内容,设置它的宽度占屏幕的100%，图片自适应</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">imgReset</span><span class="params">(WebView view)</span> </span>&#123;</span><br><span class="line">        view.loadUrl(<span class="string">"javascript:(function()&#123;"</span> +</span><br><span class="line">                <span class="string">"var objs = document.getElementsByTagName('img'); "</span> +</span><br><span class="line">                <span class="string">"for(var i=0;i&lt;objs.length;i++)  "</span> +</span><br><span class="line">                <span class="string">"&#123;"</span></span><br><span class="line">                + <span class="string">"var img = objs[i];   "</span></span><br><span class="line">                + <span class="string">"    img.style.maxWidth = '100%';   "</span></span><br><span class="line">                + <span class="string">"    img.style.height = 'auto';   "</span></span><br><span class="line">                + <span class="string">"&#125;"</span> +</span><br><span class="line">                <span class="string">"&#125;)()"</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-设置WebViewClient"><a href="#4-设置WebViewClient" class="headerlink" title="4.设置WebViewClient"></a>4.设置WebViewClient</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">webview.setWebViewClient(<span class="keyword">new</span> WebViewClient() &#123;</span><br><span class="line">            <span class="comment">//复写shouldOverrideUrlLoading()方法，设置打开网页时不调用系统浏览器， 直接在WebView中显示</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldOverrideUrlLoading</span><span class="params">(WebView view, String url)</span> </span>&#123;</span><br><span class="line">                view.loadUrl(url);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPageFinished</span><span class="params">(WebView view, String url)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">super</span>.onPageFinished(view, url);</span><br><span class="line">                <span class="comment">// html加载完成之后，添加监听图片的点击js函数</span></span><br><span class="line">                addImageClickListner(view);</span><br><span class="line">                imgReset(view);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        webView.loadData(<span class="string">"&lt;!DOCTYPE html&gt;&lt;title&gt;&lt;/title&gt;"</span>, <span class="string">"text/html"</span>, <span class="keyword">null</span>);</span><br></pre></td></tr></table></figure>
<p>至此， <strong>WebView</strong>  加载的网页中，图片点击事件处理已经完成。需要注意的是，使用此方法来允许JavaScript控制主机应用程序。这是一个强大的功能，但也为面向JELLY_BEAN或更早版本的应用程序提供安全风险。如果应用程序在运行Android 4.2的设备上运行，那么定位比<a href="https://developer.android.google.cn/reference/android/os/Build.VERSION_CODES.html#JELLY_BEAN" target="_blank" rel="noopener">JELLY_BEAN</a>更晚的版本的应用程序仍然存在漏洞。使用此方法的最安全的方法是将<a href="https://developer.android.google.cn/reference/android/os/Build.VERSION_CODES.html#JELLY_BEAN_MR1" target="_blank" rel="noopener">JELLY_BEAN_MR1</a>作为目标，并确保只有在Android 4.2或更高版本上运行时才会调用该方法。</p>
<p>使用这些较旧的版本，JavaScript可以使用反射来访问注入对象的公共字段。在包含非信任内容的  <strong>WebView</strong>  中使用此方法可能允许攻击者以非预期的方式操纵主机应用程序，并使用主机应用程序的权限执行Java代码。在可能包含不可信内容的  <strong>WebView</strong>  中使用此方法时要格外小心。</p>
<h3 id="二、实现web文件下载功能"><a href="#二、实现web文件下载功能" class="headerlink" title="二、实现web文件下载功能"></a>二、实现web文件下载功能</h3><p> <strong>WebView</strong>  控制网页在应用中进行显示的时候，如果碰到下载链接，点击将不会有任何效果，这是因为默认状态下 <strong>WebView</strong> 没有开启文件下载的功能，如果要实现文件下载的功能，需要设置WebView的DownloadListener，自己实现DownloadListener的接口来达到文件的下载。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">DownloadListener</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDownloadStart</span><span class="params">(String url, String userAgent,</span></span></span><br><span class="line"><span class="function"><span class="params">            String contentDisposition, String mimetype, <span class="keyword">long</span> contentLength)</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th style="text-align:left">参数</th>
<th style="text-align:right">类型</th>
<th style="text-align:center">释义</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">url</td>
<td style="text-align:right">String</td>
<td style="text-align:center">要下载的内容的完整网址</td>
</tr>
<tr>
<td style="text-align:left">userAgent</td>
<td style="text-align:right">String</td>
<td style="text-align:center">用于下载的用户代理</td>
</tr>
<tr>
<td style="text-align:left">contentDisposition</td>
<td style="text-align:right">String</td>
<td style="text-align:center">配置http头部信息（如果有的话）</td>
</tr>
<tr>
<td style="text-align:left">mimetype</td>
<td style="text-align:right">String</td>
<td style="text-align:center">从服务器获知的内容的MIME类型</td>
</tr>
<tr>
<td style="text-align:left">contentLength</td>
<td style="text-align:right">long</td>
<td style="text-align:center">从服务器获知的文件大小</td>
</tr>
</tbody>
</table>
<h4 id="1-实现DownloadListener接口"><a href="#1-实现DownloadListener接口" class="headerlink" title="1.实现DownloadListener接口"></a>1.实现DownloadListener接口</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyDownLoadListener</span> <span class="keyword">implements</span> <span class="title">DownloadListener</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Context mContext;</span><br><span class="line"></span><br><span class="line">    WebViewDownLoadListener(Context mContext) &#123;</span><br><span class="line">        <span class="keyword">this</span>.mContext = mContext;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDownloadStart</span><span class="params">(String url, String userAgent, String contentDisposition, String mimetype, <span class="keyword">long</span> contentLength)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//这里进行文件下载的处理</span></span><br><span class="line">        <span class="comment">//1、先判断手机是否有SD卡用于存储文件</span></span><br><span class="line">         <span class="keyword">if</span> (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) &#123;</span><br><span class="line">          <span class="comment">//如果没有则提醒用户</span></span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//2、通过url进行文件下载，这里使用的是AsyncTask</span></span><br><span class="line">        DownloaderTask task = <span class="keyword">new</span> DownloaderTask();</span><br><span class="line">        task.execute(url);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h4 id="2-新建DownloaderTask-继承AsyncTask并重写其方法"><a href="#2-新建DownloaderTask-继承AsyncTask并重写其方法" class="headerlink" title="2.新建DownloaderTask 继承AsyncTask并重写其方法"></a>2.新建DownloaderTask 继承AsyncTask并重写其方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">DownloaderTask</span> <span class="keyword">extends</span> <span class="title">AsyncTask</span>&lt;<span class="title">String</span>, <span class="title">Void</span>, <span class="title">String</span>&gt; </span>&#123;</span><br><span class="line">       <span class="comment">//文件存储路径（自定义）</span></span><br><span class="line">       String dpath = AppConfig.attach_path;</span><br><span class="line"></span><br><span class="line">       DownloaderTask() &#123;</span><br><span class="line"></span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="meta">@Override</span></span><br><span class="line">       <span class="function"><span class="keyword">protected</span> String <span class="title">doInBackground</span><span class="params">(String... params)</span> </span>&#123;</span><br><span class="line">           String url = params[<span class="number">0</span>];</span><br><span class="line">           String[] tmpname = url.split(<span class="string">"/"</span>);</span><br><span class="line">           String fileName = tmpname[<span class="number">4</span>] + <span class="string">"_"</span> + url.substring(url.lastIndexOf(<span class="string">"/"</span>) + <span class="number">1</span>);</span><br><span class="line">           <span class="keyword">try</span> &#123;</span><br><span class="line">               fileName = URLDecoder.decode(fileName, <span class="string">"UTF-8"</span>);</span><br><span class="line">           &#125; <span class="keyword">catch</span> (UnsupportedEncodingException e) &#123;</span><br><span class="line">               e.printStackTrace();</span><br><span class="line">           &#125;</span><br><span class="line">           File file = <span class="keyword">new</span> File(dpath, fileName);</span><br><span class="line">           <span class="keyword">if</span> (file.exists()) &#123;</span><br><span class="line">               Log.i(<span class="string">"tag"</span>, <span class="string">"The file has already exists."</span>);</span><br><span class="line">               <span class="keyword">return</span> fileName;</span><br><span class="line">           &#125;</span><br><span class="line">           <span class="keyword">try</span> &#123;</span><br><span class="line">               URL realUrl = <span class="keyword">new</span> URL(url);</span><br><span class="line">               HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();</span><br><span class="line">               <span class="keyword">if</span> (conn.getResponseCode() == <span class="number">200</span>) &#123;</span><br><span class="line">                   <span class="comment">//获取文件流，并写入SD卡</span></span><br><span class="line">                   InputStream input = conn.getInputStream();</span><br><span class="line">                   writeToSDCard(fileName, input);</span><br><span class="line">                   input.close();</span><br><span class="line">                   <span class="keyword">return</span> fileName;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                   <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">                &#125;</span><br><span class="line">           &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">               e.printStackTrace();</span><br><span class="line">               <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="meta">@Override</span></span><br><span class="line">       <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCancelled</span><span class="params">()</span> </span>&#123;</span><br><span class="line">           <span class="keyword">super</span>.onCancelled();</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="meta">@Override</span></span><br><span class="line">       <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPostExecute</span><span class="params">(String result)</span> </span>&#123;</span><br><span class="line">           <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">           <span class="keyword">super</span>.onPostExecute(result);</span><br><span class="line">           <span class="keyword">if</span> (result == <span class="keyword">null</span>) &#123;</span><br><span class="line">               Toast t = Toast.makeText(mContext, <span class="string">"连接错误！请稍后再试！"</span>, Toast.LENGTH_LONG);</span><br><span class="line">               t.setGravity(Gravity.CENTER, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">               t.show();</span><br><span class="line">               <span class="keyword">return</span>;</span><br><span class="line">           &#125;</span><br><span class="line">           Toast t = Toast.makeText(mContext, <span class="string">"已保存到SD卡。"</span>, Toast.LENGTH_LONG);</span><br><span class="line">           t.setGravity(Gravity.CENTER, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">           t.show();</span><br><span class="line"></span><br><span class="line">           File file = <span class="keyword">new</span> File(dpath, result);</span><br><span class="line">           Log.i(<span class="string">"tag"</span>, <span class="string">"Path="</span> + file.getAbsolutePath());</span><br><span class="line">           <span class="comment">//获取intent跳转，打开本地文件</span></span><br><span class="line">           Intent intent = getFileIntent(file);</span><br><span class="line"></span><br><span class="line">           <span class="comment">//捕获异常并处理掉，防止APP崩溃</span></span><br><span class="line">           <span class="keyword">try</span> &#123;</span><br><span class="line">               mContext.startActivity(intent);</span><br><span class="line">           &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">               Toast.makeText(mContext, <span class="string">"没有找到可匹配的程序"</span>, Toast.LENGTH_SHORT).show();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="meta">@Override</span></span><br><span class="line">       <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPreExecute</span><span class="params">()</span> </span>&#123;</span><br><span class="line">           <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">           <span class="keyword">super</span>.onPreExecute();</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="meta">@Override</span></span><br><span class="line">       <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onProgressUpdate</span><span class="params">(Void... values)</span> </span>&#123;</span><br><span class="line">           <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">           <span class="keyword">super</span>.onProgressUpdate(values);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h4 id="3-写入文件到本地和打开文件的方法"><a href="#3-写入文件到本地和打开文件的方法" class="headerlink" title="3.写入文件到本地和打开文件的方法"></a>3.写入文件到本地和打开文件的方法</h4><h5 id="3-1-写入文件到本地"><a href="#3-1-写入文件到本地" class="headerlink" title="3.1 写入文件到本地"></a>3.1 写入文件到本地</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">writeToSDCard</span><span class="params">(String fileName, InputStream input)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) &#123;</span><br><span class="line">            File file = <span class="keyword">new</span> File(AppConfig.attach_path, fileName);</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(file);</span><br><span class="line">                <span class="keyword">byte</span>[] b = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">2048</span>];</span><br><span class="line">                <span class="keyword">int</span> j = <span class="number">0</span>;</span><br><span class="line">                <span class="keyword">while</span> ((j = input.read(b)) != -<span class="number">1</span>) &#123;</span><br><span class="line">                    fos.write(b, <span class="number">0</span>, j);</span><br><span class="line">                &#125;</span><br><span class="line">                fos.flush();</span><br><span class="line">                fos.close();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                <span class="comment">// TODO Auto-generated catch block</span></span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            Log.i(<span class="string">"tag"</span>, <span class="string">"NO SDCard."</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h5 id="3-2-打开文件"><a href="#3-2-打开文件" class="headerlink" title="3.2 打开文件"></a>3.2 打开文件</h5><blockquote>
<p>请注意Android7.0以后权限机制进行了调整，为了提高文件访问的安全性，限制了应用通过file://方式直接对外提供文件路径的功能，向应用外部提供这种uri会直接导致应用崩溃。替代方案是使用FileProvider通过content://方式提供这些uri，并进行临时访问授权，对应的目录要在xml中注册才行。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">private</span> Intent <span class="title">getFileIntent</span><span class="params">(File file)</span> </span>&#123;</span><br><span class="line">        Uri uri = Uri.fromFile(file);</span><br><span class="line">        String type = getMIMEType(file);</span><br><span class="line">        Log.i(<span class="string">"tag"</span>, <span class="string">"type="</span> + type);</span><br><span class="line">        <span class="comment">//判断是否是Android N(7.0)以及更高版本</span></span><br><span class="line">        Intent intent = <span class="keyword">new</span> Intent(Intent.ACTION_VIEW);</span><br><span class="line">        intent.addCategory(<span class="string">"android.intent.category.DEFAULT"</span>);</span><br><span class="line">        <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= <span class="number">24</span>) &#123;</span><br><span class="line">            <span class="comment">//关于FileProvider的相关配置，这里就不做介绍</span></span><br><span class="line">            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);</span><br><span class="line">            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);</span><br><span class="line">            Uri contentUri = FileProvider.getUriForFile(mContext, <span class="string">"XXX.YYYY.ZZ.fileProvider"</span>, file);</span><br><span class="line">            intent.setDataAndType(contentUri, type);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);</span><br><span class="line">            intent.setDataAndType(uri, type);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> intent;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//获取文件类型</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> String <span class="title">getMIMEType</span><span class="params">(File f)</span> </span>&#123;</span><br><span class="line">        String type = <span class="string">""</span>;</span><br><span class="line">        String fName = f.getName();</span><br><span class="line">      <span class="comment">/* 取得扩展名 */</span></span><br><span class="line">        String end = fName.substring(fName.lastIndexOf(<span class="string">"."</span>) + <span class="number">1</span>, fName.length()).toLowerCase();</span><br><span class="line">      <span class="comment">/* 依扩展名的类型决定MimeType */</span></span><br><span class="line">        <span class="keyword">switch</span> (end) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"pdf"</span>:</span><br><span class="line">                type = <span class="string">"application/pdf"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"m4a"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"mp3"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"mid"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"xmf"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"ogg"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"wav"</span>:</span><br><span class="line">                type = <span class="string">"audio/*"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"3gp"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"mp4"</span>:</span><br><span class="line">                type = <span class="string">"video/*"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"jpg"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"gif"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"png"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"jpeg"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"bmp"</span>:</span><br><span class="line">                type = <span class="string">"image/*"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"apk"</span>:</span><br><span class="line">        <span class="comment">/* android.permission.INSTALL_PACKAGES */</span></span><br><span class="line">                type = <span class="string">"application/vnd.android.package-archive"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"pptx"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"ppt"</span>:</span><br><span class="line">                type = <span class="string">"application/vnd.ms-powerpoint"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"docx"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"doc"</span>:</span><br><span class="line">                type = <span class="string">"application/msword"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"xlsx"</span>:</span><br><span class="line">            <span class="keyword">case</span> <span class="string">"xls"</span>:</span><br><span class="line">                type = <span class="string">"application/vnd.ms-excel"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">         <span class="comment">/*如果无法直接打开，就跳出软件列表给用户选择 */</span></span><br><span class="line">                type = <span class="string">"*/*"</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> type;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h3 id="三、处理web页面的弹框"><a href="#三、处理web页面的弹框" class="headerlink" title="三、处理web页面的弹框"></a>三、处理web页面的弹框</h3><p>每个web页面都会有自己的逻辑，其中涉及到弹框的处理，默认情况下，<strong>Android WebView</strong>是不支持 <strong>js</strong> 的Alert(),Confirm(),Prompt()函数的弹出提示框，需要我们设置<a href="https://developer.android.google.cn/reference/android/webkit/WebChromeClient.html" target="_blank" rel="noopener">WebChromeClient</a> 对象来完成。这里我们可以分为以下两种情况来讨论。</p>
<h4 id="1-不对弹框进行任何处理"><a href="#1-不对弹框进行任何处理" class="headerlink" title="1.不对弹框进行任何处理"></a>1.不对弹框进行任何处理</h4><p>这种很简单，直接设置就行</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">webView.setWebChromeClient(<span class="keyword">new</span> WebChromeClient());</span><br></pre></td></tr></table></figure>
<h4 id="2-处理弹框样式"><a href="#2-处理弹框样式" class="headerlink" title="2.处理弹框样式"></a>2.处理弹框样式</h4><p>重写WebChromeClient的下列方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//警告框</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onJsAlert</span><span class="params">(WebView view, String url, String message, JsResult result)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 这里处理交互逻辑</span></span><br><span class="line">    <span class="comment">// 如果客户端返回true，WebView将假定客户端将处理对话框。如果客户端返回false，它将继续执行</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>; </span><br><span class="line">&#125; </span><br><span class="line"><span class="comment">//确认对话框</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onJsConfirm</span><span class="params">(WebView view, String url, String message, JsResult result)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125; </span><br><span class="line"><span class="comment">//提示对话框</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onJsPrompt</span><span class="params">(WebView view, String url, String message, String defaultValue, JsPromptResult result)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//告诉客户端显示一个对话框来确认离开当前页面的导航。这是onbeforeunload javascript事件的结果。</span></span><br><span class="line"><span class="comment">//如果客户端返回true，WebView将假定客户端将处理确认对话框并调用相应的JsResult方法。</span></span><br><span class="line"><span class="comment">//如果客户端返回false，则默认值true将返回到javascript以接受离开当前页面的导航。</span></span><br><span class="line"><span class="comment">//默认行为是返回false。将JsResult设置为true将离开当前页面，false将取消导航。</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onJsBeforeUnload</span><span class="params">(WebView view, String url, String message, JsResult result)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Leason
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://www.leason.top/2018/01/09/如何优雅的使用WebView/" title="如何优雅的使用WebView">http://www.leason.top/2018/01/09/如何优雅的使用WebView/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"><i class="fa fa-tag"></i> Android</a>
          
            <a href="/tags/WebView/" rel="tag"><i class="fa fa-tag"></i> WebView</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/12/05/候鸟和鱼/" rel="next" title="候鸟和鱼">
                <i class="fa fa-chevron-left"></i> 候鸟和鱼
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/19/贰零壹捌/" rel="prev" title="贰零壹捌">
                贰零壹捌 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjMyMC84ODgx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/pics.jpg"
                alt="Leason" />
            
              <p class="site-author-name" itemprop="name">Leason</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
          </div>

          
          

          
          
		  

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、处理web页面中的图片点击事件"><span class="nav-text">一、处理web页面中的图片点击事件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-定义JavaScript接口类"><span class="nav-text">1.定义JavaScript接口类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-在WebView中添加JavascriptInterface"><span class="nav-text">2.在WebView中添加JavascriptInterface</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-新建图片遍历和处理的方法"><span class="nav-text">3.新建图片遍历和处理的方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-设置WebViewClient"><span class="nav-text">4.设置WebViewClient</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、实现web文件下载功能"><span class="nav-text">二、实现web文件下载功能</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-实现DownloadListener接口"><span class="nav-text">1.实现DownloadListener接口</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-新建DownloaderTask-继承AsyncTask并重写其方法"><span class="nav-text">2.新建DownloaderTask 继承AsyncTask并重写其方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-写入文件到本地和打开文件的方法"><span class="nav-text">3.写入文件到本地和打开文件的方法</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-1-写入文件到本地"><span class="nav-text">3.1 写入文件到本地</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-2-打开文件"><span class="nav-text">3.2 打开文件</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、处理web页面的弹框"><span class="nav-text">三、处理web页面的弹框</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-不对弹框进行任何处理"><span class="nav-text">1.不对弹框进行任何处理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-处理弹框样式"><span class="nav-text">2.处理弹框样式</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <!--<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Leason</span>
  
</div>

<!--
  <div class="powered-by">
	<p>Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a></p>
  </div>
-->







        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("HmQr5iz8kGMSFbKtjyaPuBdg-gzGzoHsz", "Ycjo961z6c7zMzEOnW48915E");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

  
<div id="hexo-helper-live2d">
  <canvas id="live2dcanvas" width="150" height="300"></canvas>
</div>
<style>
  #live2dcanvas{
    position: fixed;
    width: 150px;
    height: 300px;
    opacity:0.7;
    right: 0px;
    z-index: 999;
    pointer-events: none;
    bottom: -20px;
  }
</style>
<script type="text/javascript" src="/live2d/device.min.js"></script>
<script type="text/javascript">
const loadScript = function loadScript(c,b){var a=document.createElement("script");a.type="text/javascript";"undefined"!=typeof b&&(a.readyState?a.onreadystatechange=function(){if("loaded"==a.readyState||"complete"==a.readyState)a.onreadystatechange=null,b()}:a.onload=function(){b()});a.src=c;document.body.appendChild(a)};
(function(){
  if((typeof(device) != 'undefined') && (device.mobile())){
    var trElement = document.getElementById('hexo-helper-live2d');
    trElement.parentNode.removeChild(trElement);
    return;
  }else
    if (typeof(device) === 'undefined') console.error('Cannot find current-device script.');
  loadScript("/live2d/script.js", function(){loadlive2d("live2dcanvas", "/live2d/assets/wanko.model.json", 0.5);});
})();
</script>

</body>
</html>
